package org.interfaceadaptation.parameter.match.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.interfaceadaptation.parameter.Parameter;
import org.interfaceadaptation.parameter.Parameters;
import org.interfaceadaptation.parameter.match.ExpressionMatcher;
import org.interfaceadaptation.parameter.match.ParametersMatcher;

public class ParametersMatcherImpl implements ParametersMatcher {

    private List<ExpressionMatcher> parameterMatchers = new ArrayList<ExpressionMatcher>(
            Arrays.asList(new StrichNameParameterMatcher()));

    @Override
    public boolean match(Parameters one, Parameters other) {
        clearParametersAssociations(one);
        clearParametersAssociations(other);
        if (tryMatchParameters(one, other)) {
            return true;
        }
        else {
            clearParametersAssociations(one);
            clearParametersAssociations(other);
            return false;
        }
    }
    
    public boolean tryMatchParameters(Parameters one, Parameters other) {
        if (one.size() != other.size()) {
            return false;
        }
        for (Parameter oneParameter : one) {
            boolean parameterMatch = false;
            for (Parameter otherParameter : other) {
                if (tryMatchParameter(oneParameter,otherParameter)) {
                    parameterMatch = true;  
                    break;
                }
            }
            if (! parameterMatch) {
              return false;    
            }
        }
        return true;
    }

    private boolean tryMatchParameter(Parameter one, Parameter other) {
        for (ExpressionMatcher parameterMatcher : getExpressionMatchers()) {
            if (parameterMatcher.match(one, other)) {
                return true;
            }
        }
        return false;
    }

    private void clearParametersAssociations(Parameters one) {
        for (Parameter oneParameter : one) {
            oneParameter.setAssociated(null);
        }
    }

    @Override
    public List<ExpressionMatcher> getExpressionMatchers() {
        return parameterMatchers;
    }

}
